/**
 * Created by huotaol on 2017/4/28.
 */

import {call, put, takeLatest} from "redux-saga/effects";
import {parseGetParam, request} from "../../../common/util/RequestUtil";
import * as types from "../../constant/ActionType";
import * as Url from "../../constant/Url";
import * as HomePageAction from "../action/homePage";

function* fetchAreaList() {
    let data = [];
    console.log('fetch area list');
    try {
        const url = Url.BASE_URL + '/loc/get_info';
        const json = yield call(request, url);
        data = json.data;
    } catch (e) {
        setTimeout(fetchAreaList, 3000);
    } finally {
        yield put(HomePageAction.receiveAreaList(data));
    }
}


function* fetchHotCar(action) {
    let carList = [];
    try {
        const url = Url.BASE_URL + '/car/comm/m/get_hot_cars' + parseGetParam({loc: action.id});
        console.log('fetchHotCar fetchHotCar url  ' + url);
        console.log('fetchHotCar fetchHotCar    ' + JSON.stringify(action));

        const json = yield call(request, url,);
        console.log('fetchHotCar fetchHotCar  json  ' + JSON.stringify(json));
        const data = json.data;
        const imgPrefix = data.imgPrefix;
        const list = data.list;
        carList = list.map(item => Object.assign({}, item, {imgName: imgPrefix + item.imgName}));
    } catch (e) {

    } finally {
        yield put(HomePageAction.hotCarList(carList));
    }
}

export default [takeLatest(types.AREA_REQUEST, fetchAreaList), takeLatest(types.SELECTED_AREA, fetchHotCar)];
